#include "user_timer.h"

SysTimerType    SysTimerBuf[SysTimerNum];
uint16_t SysTimer10usCnt;
uint16_t SysTimer_Read()
{
    return TMR0_ReadTimer();
}
void SysTimer_Init(void)
{
    unsigned char i=0;
    for(i=0;i<SysTimerNum;i++)
    {
        SysTimerBuf[i].TimerEnable=false;
        SysTimerBuf[i].TimerSetMs=0;
        SysTimerBuf[i].TimerNowMs=0;
        SysTimerBuf[i].TimerOccur=false;
    }
    SysTimer10usCnt=SysTimer_Read();
}

//100us
void SysTimer_Cyc()
{
    unsigned char i=0;
    uint16_t TempTimer10usCnt=SysTimer_Read();
    
    if(TempTimer10usCnt>=499)
    {
//        PIR0bits.TMR0IF=0;
        TMR0_WriteTimer(0);
    }
    else
    {   
        return;
    }
        
    
    for(i=0;i<SysTimerNum;i++)
    {
        if(SysTimerBuf[i].TimerEnable==true&&SysTimerBuf[i].TimerOccur==false)
        {
            SysTimerBuf[i].TimerNowMs+=1;//1 ms
            if(SysTimerBuf[i].TimerNowMs>=SysTimerBuf[i].TimerSetMs)
            {
                SysTimerBuf[i].TimerSetMs=0;
                SysTimerBuf[i].TimerNowMs=0;                
                SysTimerBuf[i].TimerOccur=true; 
                SysTimerBuf[i].TimerEnable=false;
            }
        }
    }
}

void SysTimer_Set(SysTimerType *p_sys_timer,unsigned int SetMs)
{
    p_sys_timer->TimerSetMs=SetMs;
    p_sys_timer->TimerOccur=false;
    p_sys_timer->TimerEnable=false;
    p_sys_timer->TimerNowMs=0;
}

void SysTimer_Enable(SysTimerType *p_sys_timer,bool state)
{
        p_sys_timer->TimerEnable=state;
}